// src/utils/ajax.js
function ajaxRequest(method, url, data = {}) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()

        // 如果是 GET 请求，将参数拼接到 URL 上
        if (method === 'GET' && data && Object.keys(data).length > 0) {
            const query = Object.entries(data)
                .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
                .join('&')
            url += (url.includes('?') ? '&' : '?') + query
        }

        xhr.open(method, url, true)

        // 设置请求头（根据需要可以调整）
        xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')

        // 如果有 token，可以在这里添加
        const token = localStorage.getItem('token')
        if (token) {
            xhr.setRequestHeader('JwtName', `${token}`) //自定义JwtName
        }

        // 监听请求完成
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        const response = JSON.parse(xhr.responseText)
                        resolve(response)
                    } catch (e) {
                        resolve(xhr.responseText)
                    }
                } else {
                    reject({
                        status: xhr.status,
                        message: xhr.statusText,
                        response: xhr.responseText
                    })
                }
            }
        }

        xhr.onerror = () => reject({ message: '网络错误' })

        // 发送请求体（GET 无需 body）
        if (method === 'GET' || method === 'DELETE') {
            xhr.send()
        } else {
            xhr.send(JSON.stringify(data))
        }
    })
}

// axios 风格 API
const ajax = {
    get: (url, params) => ajaxRequest('GET', url, params),
    post: (url, data) => ajaxRequest('POST', url, data),
    put: (url, data) => ajaxRequest('PUT', url, data),
    delete: (url, data) => ajaxRequest('DELETE', url, data)
}

export default ajax

//使用实例
//await ajax.get('/user', { id: 1 })
//await ajax.post('/login', { username: 'admin', password: '123' })
//await ajax.put('/user/1', { name: 'Tom' })
//await ajax.delete('/user/1')

